package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.example.demo.entity.UserBean;
import com.example.demo.entity.dto.UserLoginDTO;
import com.example.demo.dao.IUserLoginDao;
import com.example.demo.error.costom.PhoneNumberAlreadyExistsException;
import com.example.demo.mapper.UsersMapper;
import com.example.demo.service.IUserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/*
 *
 *   @Author:max
 *   @Date: 2024/3/4-03-04-21:02
 *
 */
@Service
public class UserLoginServiceImpl implements IUserLoginService {

    @Autowired
    private IUserLoginDao iUserLoginDao;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public UserLoginDTO userLoginByPass(UserBean userBean) {

        //用户登录
        UserBean bean = iUserLoginDao.selectByNameAndPass(userBean);
        //如果为空证明没有查询到用户
        if(bean == null){
            return null;
        }
        UserLoginDTO userLoginDTO = new UserLoginDTO();
        //抹掉密码
        BeanUtil.copyProperties(bean,userLoginDTO);

        //信息脱敏
        userLoginDTO.setPhone(DesensitizedUtil.mobilePhone(userLoginDTO.getPhone()));
        userLoginDTO.setIdCard(DesensitizedUtil.idCardNum(userLoginDTO.getIdCard(),3,6));
        return userLoginDTO;
    }


    @Override
    public boolean userRegisterByPhone(UserBean userBean) {
        //先校验是否有这个手机号
        UserBean userBeanByPhone = iUserLoginDao.selectByPhone(userBean);
        //如果有
        if(userBeanByPhone != null){
            //手机号已存在异常
            throw new PhoneNumberAlreadyExistsException();
        }
        //得到md5加密对象
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        //生成一个盐值（随机的20个字符）
        String salt = IdUtil.simpleUUID().substring(0,20);
        //（设置盐值）
        md5.setSalt(salt.getBytes());
        //digest 消化 Hex 16进制(对注册密码进行加密)
        String md5Pass = md5.digestHex(userBean.getPassword());
        userBean.setPassword(md5Pass);//放入加密后的密码
        userBean.setSalt(salt);//放入盐值

        iUserLoginDao.insertUserByPhone(userBean);
        return true;
    }

}
